package sentinel;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

import java.util.ArrayList;
import java.util.List;

public class Sentinel {
    public static void main(String[] args) {
        initSentinel();

        for (int i = 0; i < 10; i++) {
            try (Entry helloSentinel = SphU.entry("resourceName")){
                System.out.println("hello sentinel: " + i);
            } catch (BlockException e) {
                System.out.println("blocked: " + i );
            }
        }
        for (int i = 0; i < 10; i++) {
            try (Entry helloSentinel = SphU.entry("resourceName2")){
                System.out.println("hello sentinel2: " + i);
            } catch (BlockException e) {
                System.out.println("blocked2: " + i );
            }
        }
    }

    private static void initSentinel() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("resourceName");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(5);
        rules.add(rule);
        FlowRule rule2 = new FlowRule();
        rule2.setResource("resourceName2");
        rule2.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule2.setCount(6);
        rules.add(rule2);
        FlowRuleManager.loadRules(rules);
    }
}
